<template>
  <div class="app-container">
    <el-form :inline="true" :model="getFormDate" class="demo-form-inline">
      <el-form-item>
        <el-input size="mini" v-model="getFormDate.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-input size="mini" v-model="getFormDate.code" placeholder="请输入编码"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="getUsers" size="mini">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button style="margin-bottom: 5px;" size="mini" @click="add">新增</el-button>
    <el-button style="margin-bottom: 5px;" size="mini" @click="handlerBatchDelete">批量删除</el-button>
    <el-table size="mini" :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" @click="setPermission(scope.$index, scope.row)">权限设置</el-button> -->
          <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <el-image style="width: 70px; height: 70px" :src="scope.row.image ? scope.row.image : ''"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="category.name" label="分类">
      </el-table-column>
      <el-table-column prop="number" label="数量">
      </el-table-column>
      <el-table-column prop="price" label="价格">
      </el-table-column>
      <el-table-column prop="content" label="介绍">
      </el-table-column>
    </el-table>
    <el-pagination style="float: right;margin-top: 5px;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize"
      layout="prev, pager, next, jumper" :total="totalNum">
    </el-pagination>
    <el-dialog title="添加" :visible.sync="dialogVisibleAdd" width="30%">
      <el-form :model="addFormData" label-width="80px" ref="addFormData">
        <el-form-item label="图片">
          <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="addFormData.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="addFormData.categoryId" placeholder="请选择">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="addFormData.number" placeholder="请输入数量"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="addFormData.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input type="textarea" :rows="3" v-model="addFormData.content" placeholder="请输入介绍"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="createFruit">确认</el-button>
          <el-button @click="resetFormAdd('addFormData')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="修改" :visible.sync="dialogVisibleUpdate" width="30%">
      <el-form :model="updateFormData" label-width="80px">
        <el-form-item label="图片">
          <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="updateFormData.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="updateFormData.categoryId" placeholder="请选择">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="updateFormData.number" placeholder="请输入数量"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="updateFormData.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input type="textarea" :rows="3" v-model="updateFormData.content" placeholder="请输入介绍"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="updateFruit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="权限设置" :visible.sync="dialogVisibleSetPermisssion" width="30%">
      <el-tree ref="treeData" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="defaultCheckedKeys" :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleSetPermisssion = false">取 消</el-button>
        <el-button size="mini" @click="getAllCheckedKeys">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFruitByPage, deleteFruit, getFruitById, updateFruitById,
  batchDeleteFruit, addFruit
} from "@/api/fruit.js"
import {
  getCategoryByPage
} from "@/api/category.js"
export default {
  data() {
    return {
      list: null,
      listLoading: true,
      getFormDate: {},
      roles: [],
      tableData: [],
      multipleSelection: [],
      ids: [],
      imageUrl: "",
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogVisibleAdd: false,
      dialogVisibleUpdate: false,
      dialogVisibleSetPermisssion: false,
      updateFormData: {},
      addFormData: {
        username: '',
        password: '',
        nickName: '',
        gender: '',
        mobile: '',
        email: '',
        roles: '',
      },
      uploadAction: "/api/upload",
      defaultExpandedKeys: [],
      defaultCheckedKeys: [],
      pageSize: 10,
      currentPage: 1,
      totalNum: 0,
      updateId: ''
    }
  },
  created() {
    this.initTableData()
    this.initCategory()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.uploadId = res.data.id
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data
      this.addFormData.image = res.data
      this.updateFormData.image = res.data
      console.log("this.imageUrl", this.imageUrl);
    },
    initCategory() {
      getCategoryByPage({ page: 1, size: 100 }).then(res => {
        this.categoryList = res.data.data.records
      })
    },
    setPermission(index, row) {
      this.defaultCheckedKeys = []
      // if (row.permissionList) {
      //   this.defaultExpandedKeys = row.permissionList.map(item => {
      //     return item.id
      //   })
      //   this.defaultCheckedKeys = this.defaultExpandedKeys
      // }
      getPermissionByFruitId(row.id).then(res => {
        if (res.data.code == 200) {
          if (res.data.data.length > 0) {
            this.defaultExpandedKeys = res.data.data.map(item => {
              return item.id
            })
            this.defaultCheckedKeys = this.defaultExpandedKeys
          }
        }
      })
      this.dialogVisibleSetPermisssion = true
      this.updateId = row.id
    },
    initTreeDate() {
      getPermissionTreeList().then(res => {
        if (res.data.code == 200) {
          this.treeData = res.data.data
        }
      })
    },
    resetFormAdd(formName) {
      this.addFormData = {}
      this.$refs[formName].resetFields();
    },
    createFruit() {
      let senddata = {
        ...this.addFormData,
        image: this.imageUrl
      }
      addFruit(senddata).then(res => {
        if (res.data.code == 200) {
          this.$message.success("添加成功")
          this.dialogVisibleAdd = false
          this.initTableData();
        }
      })
    },
    getAllCheckedKeys() {
      const treeDataRef = this.$refs.treeData;
      // getCheckedNodes:全选的集合，getHalfCheckedNodes半选的集合
      // , ...treeDataRef.getHalfCheckedNodes()
      const treeDataList = [...treeDataRef.getCheckedNodes(), ...treeDataRef.getHalfCheckedNodes()];
      let tableDataIds = treeDataList.map(item => {
        return item.id
      })
      setPermissions(this.updateId, tableDataIds).then(res => {
        if (res.data.code == 200) {
          this.$message.success("权限设置成功")
          this.dialogVisibleSetPermisssion = false
        }
      })
    },
    updateFruit() {
      updateFruitById(this.updateFormData).then(res => {
        if (res.data.code == 200) {
          this.$message.success("修改成功")
          this.dialogVisibleUpdate = false
          this.initTableData();
        }
      })
    },
    handlerBatchDelete() {
      if (this.multipleSelection.length > 0) {
        this.ids = this.multipleSelection.map(item => {
          return item.id
        })
        batchDeleteFruit(this.ids).then(res => {
          if (res.data.code == 200) {
            this.$message.success("批量删除成功")
            this.initTableData()
          }
        })
      } else {
        this.$message.warning("请先选择删除项")
      }
    },
    initTableData(page) {
      let senddata = {
        ...this.getFormDate,
        size: this.pageSize,
        page: page ? page : this.currentPage
      }
      getFruitByPage(senddata).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.records
          this.totalNum = res.data.data.total
          this.defaultExpandedKeys = res.data.data.records.map(item => {
            return item.id
          })
        }
      })
    },
    add() {
      this.dialogVisibleAdd = true
    },
    handleEdit(index, row) {
      this.dialogVisibleUpdate = true
      getFruitById(row.id).then(res => {
        if (res.data.code == 200) {
          this.updateFormData = res.data.data
          this.imageUrl = res.data.data.image
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFruit(row.id).then(res => {
          if (res.data.code == 200) {
            this.$message.success("删除成功")
            this.initTableData();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getUsers() {
      this.initTableData();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.initTableData(val)
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    }
  }
}
</script>

<style>
.el-dialog {
  position: absolute;
  top: -40px;
  margin-left: 550px;
}
</style>